﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.Utils;
using DevExpress.Data.Filtering;
using System.Reflection;
using DevExpress.XtraEditors.Registrator;
using DevExpress.XtraEditors.Drawing;
using DevExpress.XtraEditors.ViewInfo;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Base;

namespace QuanLyThuNgan
{
    public partial class Frm_HoanTien : DevExpress.XtraEditors.XtraForm
    {
        public Frm_HoanTien()
        {
            InitializeComponent();
        }

        string sTenSearch = "";
        string sColSearch;
        public static string sIDSearch = "";
        public static string sTenValueSearch = "";
        string sTenTam, sColTam;

        DMLyDoHoanCTL lyDoHoanCtl = new DMLyDoHoanCTL();
        HoanTienCTL hoanTienCtl = new HoanTienCTL();
        HoanTienDTO hoanTienDto = new HoanTienDTO();
        private void Frm_HoanTien_Load(object sender, EventArgs e)
        {
            //load ngay kham hien tai----------------------
            dateNgayKham.DateTime = Uit.it_Date.CurrentDate2();
            //load ngay hoan------------------------------
            txtNgayHoan.Text = Uit.it_Date.CurrentDate();

            //load gridlookupedit danh muc ly do hoan-----------------------
            DataTable dtLyDoHoan = lyDoHoanCtl.m_SelectLyDoHoan();
            ClassHelp.m_gridLookUpEdit(dtLyDoHoan, grdLyDoHoan, "TenLyDo", "IDLyDo");
            //--------------------
            m_ReadOnly();
        }
        public DataTable dtBNHoanTien; 
        private void btnTim_Click(object sender, EventArgs e)
        {
            if (txtSobn.Text != "")
            {
                hoanTienDto.SSobn = txtSobn.Text;
                DataTable dtht = hoanTienCtl.m_LoadHoanTienBafee(hoanTienDto).Tables[0];
                if (dtht.Rows.Count > 0)
                {
                    txtSohsHT.Text = dtht.Rows[0]["SoHS"].ToString();
                    txtHoTenHT.Text = dtht.Rows[0]["HoTen"].ToString();
                    txtGioiTinhHT.Text = dtht.Rows[0]["GioiTinh"].ToString();
                    txtNamSinhHT.Text = dtht.Rows[0]["NamSinh"].ToString();
                    txtDiaChiHT.Text = dtht.Rows[0]["DiaChi"].ToString();
                    txtSobnHT.Text = dtht.Rows[0]["sobn"].ToString();
                    txtNgay.Text = dtht.Rows[0]["Ngay"].ToString();
                    txtTenDonVi.Text = dtht.Rows[0]["DonVi"].ToString();
                    DataTable dthtct = hoanTienCtl.m_LoadHoanTienBafee(hoanTienDto).Tables[1];
                    gdDanhSachHoanTien.DataSource = dthtct;
                }
                else
                {
                    XtraMessageBox.Show("Thông tin không tồn tại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                if (txtSohs.Text == "")
                    if (txtSTT.Text == "")
                        return;
                hoanTienDto.SSohsTim = txtSohs.Text;
                hoanTienDto.SNgayKham = Uit.it_Parse.ToDateTime(dateNgayKham.EditValue).ToString("yyyy-MM-dd");
                hoanTienDto.ISTT = txtSTT.Text == "" ? 0 : Uit.it_Parse.ToInteger(txtSTT.Text);
                dtBNHoanTien = hoanTienCtl.m_LoadBenhnhanHoanTien(hoanTienDto).Tables[0];
                if (dtBNHoanTien.Rows.Count > 0)
                {
                    txtSohsHT.Text = dtBNHoanTien.Rows[0]["SoHS"].ToString();
                    txtHoTenHT.Text = dtBNHoanTien.Rows[0]["HoTen"].ToString();
                    txtGioiTinhHT.Text = dtBNHoanTien.Rows[0]["GioiTinh"].ToString();
                    txtNamSinhHT.Text = dtBNHoanTien.Rows[0]["NamSinh"].ToString();
                    txtDiaChiHT.Text = dtBNHoanTien.Rows[0]["DiaChi"].ToString();
                    txtSobnHT.Text = dtBNHoanTien.Rows[0]["IDNhanBenh"].ToString();
                    txtNgay.Text = dtBNHoanTien.Rows[0]["Ngay"].ToString();
                    DataTable dtHoanTienChiTiet = hoanTienCtl.m_LoadBenhnhanHoanTien(hoanTienDto).Tables[1];
                    gdDanhSachHoanTien.DataSource = dtHoanTienChiTiet;
                }
                else
                {
                    XtraMessageBox.Show("Thông tin không tồn tại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
            
            //set value------------------------------------------
            grdLyDoHoan.EditValue = -1;
            txtTongTienHoan.Text = "";
        }

        private void gvDanhSachHoanTien_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator)
            {
                if (e.RowHandle < 0)
                    e.Info.DisplayText = "";
                else
                    e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
            else
                e.Info.DisplayText = "STT";
            e.Info.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
        }

        private int iSoLuong, iTienThu,iSLHoan = 0;
        private int iTienHoan=0, iTongTienHoan=0;
        private void gvDanhSachHoanTien_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
           
            DataRow dr = gvDanhSachHoanTien.GetDataRow(gvDanhSachHoanTien.FocusedRowHandle);
            if (dr != null)
            {
                iSoLuong = Uit.it_Parse.ToInteger(dr["SoLuong"].ToString());
                iTienThu = Uit.it_Parse.ToInteger(dr["TienThu"].ToString());
                iSLHoan = Uit.it_Parse.ToInteger(dr["SoLuongHoan"].ToString());
                iTienHoan = (iSLHoan * iTienThu) / iSoLuong;
                dr["TienHoan"] = iTienHoan;
            }
            iTongTienHoan += iTienHoan;
            txtTongTienHoan.Text = Uit.it_Parse.ToString(iTongTienHoan);
            if (iTienHoan != 0)
            {
                btnXacNhan.Enabled = true;
            }
            
        }

        private void btnXacNhan_Click(object sender, EventArgs e)
        {
            //xac nhan benh nhan tiep nhan-----------------------------------
            if (txtSobn.Text == "")
            {
                if (m_checkXacNhan() == true)
                {
                    hoanTienDto.SSobn = txtSobnHT.Text;
                    hoanTienDto.SNgayHoan = Uit.it_Parse.ToDateTime(txtNgayHoan.Text).ToString("yyyy-MM-dd");
                    hoanTienDto.SGioHoan = Uit.it_Date.CurrentTime();
                    hoanTienDto.ILyDoHoan = Uit.it_Parse.ToInteger(grdLyDoHoan.EditValue.ToString());
                    hoanTienDto.IIDHoanTien = frmLogin.nd.IDNguoiDung;
                    hoanTienDto.ITongTienHoan = Uit.it_Parse.ToInteger(txtTongTienHoan.Text);
                    DataTable dtCalv = hoanTienCtl.m_SelectHoanTienCaLV(hoanTienDto);
                    foreach (DataRow dr in dtCalv.Rows)
                    {
                        if (dr != null)
                        {
                            hoanTienDto.IIDCaHoan = Uit.it_Parse.ToInteger(dr["IDCaLamViec"].ToString());
                        }
                        else
                        {
                            XtraMessageBox.Show("Không có ca làm việc", "Thông báo");
                        }
                    }
                    object idHoan = hoanTienCtl.m_InsertHoanTienMst(hoanTienDto);
                    hoanTienDto.IIDHoan = Uit.it_Parse.ToInteger(idHoan);
                    //select gia tri chi tiet---------------------------------
                    DataTable dtHTCT = (DataTable)gdDanhSachHoanTien.DataSource;
                    if (dtHTCT != null)
                    {
                        for (int i = 0; i < gvDanhSachHoanTien.RowCount; i++)
                        {
                            DataRow drct = gvDanhSachHoanTien.GetDataRow(i);
                            gvDanhSachHoanTien.MoveNext();
                            gvDanhSachHoanTien.MovePrev();

                            hoanTienDto.Sdvucode = drct["dvucode"].ToString();
                            hoanTienDto.ISoLuongHoan = Uit.it_Parse.ToInteger(drct["SoLuongHoan"].ToString());
                            hoanTienDto.ITienHoan = Uit.it_Parse.ToInteger(drct["TienHoan"].ToString());
                            hoanTienDto.INhanBenhCT = Uit.it_Parse.ToInteger(drct["dvucode"].ToString());
                            if (Uit.it_Parse.ToInteger(drct["TienHoan"].ToString()) > 0)
                            {
                                if (Uit.it_Parse.ToInteger(drct["SoLuongHoan"].ToString()) <= Uit.it_Parse.ToInteger(drct["SoLuong"].ToString()))
                                {
                                    hoanTienCtl.m_InsertHoanTienDtl(hoanTienDto);
                                    //update nhan benh chi tiet-----------------
                                    hoanTienCtl.m_UpdateNhanBenhCT(hoanTienDto);
                                    
                                }
                                else
                                {
                                    XtraMessageBox.Show("Số lượng hoàn phải nhỏ hơn hoặc bằng số lượng", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }

                            }
                        }
                    }
                    XtraMessageBox.Show("Xác nhận thành công", "Thông báo");
                    //reload danh sach hoan tien----------------------------
                    DataTable dtHoanTienChiTiet = hoanTienCtl.m_LoadBenhnhanHoanTien(hoanTienDto).Tables[1];
                    gdDanhSachHoanTien.DataSource = dtHoanTienChiTiet;
                    txtTongTienHoan.Text = "";
                }

                else
                {
                    XtraMessageBox.Show("Phải hoàn thành thông tin nhập liệu", "Thông báo");
                    return;
                }
                
            }
                //xac nhan benh nhan ngoai tru---------------------
            else
            {
                if (m_checkXacNhan() == true)
                {
                    hoanTienDto.SSobn = txtSobnHT.Text;
                    hoanTienDto.SNgayHoan = Uit.it_Parse.ToDateTime(txtNgayHoan.Text).ToString("yyyy-MM-dd");
                    hoanTienDto.SGioHoan = Uit.it_Date.CurrentTime();
                    hoanTienDto.ILyDoHoan = Uit.it_Parse.ToInteger(grdLyDoHoan.EditValue.ToString());
                    hoanTienDto.IIDHoanTien = frmLogin.nd.IDNguoiDung;
                    hoanTienDto.ITongTienHoan = Uit.it_Parse.ToInteger(txtTongTienHoan.Text);
                    DataTable dtCalv = hoanTienCtl.m_SelectHoanTienCaLV(hoanTienDto);
                    foreach (DataRow dr in dtCalv.Rows)
                    {
                        if (dr != null)
                        {
                            hoanTienDto.IIDCaHoan = Uit.it_Parse.ToInteger(dr["IDCaLamViec"].ToString());
                        }
                        else
                        {
                            XtraMessageBox.Show("Không có ca làm việc", "Thông báo");
                        }
                    }
                    object idHoan = hoanTienCtl.m_InsertHoanTienMst(hoanTienDto);
                    hoanTienDto.IIDHoan = Uit.it_Parse.ToInteger(idHoan);
                    //select gia tri chi tiet---------------------------------
                    DataTable dtHTCT = (DataTable)gdDanhSachHoanTien.DataSource;
                    if (dtHTCT != null)
                    {
                        for (int i = 0; i < gvDanhSachHoanTien.RowCount; i++)
                        {
                            DataRow drct = gvDanhSachHoanTien.GetDataRow(i);
                            gvDanhSachHoanTien.MoveNext();
                            gvDanhSachHoanTien.MovePrev();

                            hoanTienDto.Sdvucode = drct["dvucode"].ToString();
                            hoanTienDto.ISoLuongHoan = Uit.it_Parse.ToInteger(drct["SoLuongHoan"].ToString());
                            hoanTienDto.ITienHoan = Uit.it_Parse.ToInteger(drct["TienHoan"].ToString());
                            if (Uit.it_Parse.ToInteger(drct["TienHoan"].ToString()) > 0)
                            {
                                if (Uit.it_Parse.ToInteger(drct["SoLuongHoan"].ToString()) <= Uit.it_Parse.ToInteger(drct["SoLuong"].ToString()))
                                {
                                    hoanTienCtl.m_InsertHoanTienDtl(hoanTienDto);
                                }
                                else
                                {
                                    XtraMessageBox.Show("Số lượng hoàn phải nhỏ hơn hoặc bằng số lượng", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }

                            }
                        }
                    }
                    XtraMessageBox.Show("Xác nhận thành công", "Thông báo");
                    //reload danh sach hoan tien-------------------------------
                    DataTable dthtct = hoanTienCtl.m_LoadHoanTienBafee(hoanTienDto).Tables[1];
                    gdDanhSachHoanTien.DataSource = dthtct;
                    txtTongTienHoan.Text = "";
                }

                else
                {
                    XtraMessageBox.Show("Phải hoàn thành thông tin nhập liệu", "Thông báo");
                    return;
                }
            }
            btnXacNhan.Enabled = false;
        }

        #region "CheckValue"
        bool m_checkXacNhan()
        {
            bool bCheckValue = true;
            if (Uit.it_Parse.ToString(grdLyDoHoan.EditValue) == "-1" || Uit.it_Parse.ToString(grdLyDoHoan.EditValue) == "")
            {
                dxErrorProvider1.SetError(grdLyDoHoan, "Phải nhập lý do hoàn tiền");
                bCheckValue = false;
            }
            else
            {
                if (Uit.it_Parse.ToString(grdLyDoHoan.EditValue) != "-1" || Uit.it_Parse.ToString(grdLyDoHoan.EditValue) != "")
                {
                    dxErrorProvider1.ClearErrors();
                }
                
            }
            return bCheckValue;
        }

        void m_ReadOnly()
        {
            txtSohsHT.Properties.ReadOnly = true;
            txtHoTenHT.Properties.ReadOnly = true;
            txtGioiTinhHT.Properties.ReadOnly = true;
            txtNamSinhHT.Properties.ReadOnly = true;
            txtDiaChiHT.Properties.ReadOnly = true;
            txtSobnHT.Properties.ReadOnly = true;
            txtNgay.Properties.ReadOnly = true;
            txtNgayHoan.Properties.ReadOnly = true;
            txtTongTienHoan.Properties.ReadOnly = true;
            txtTenDonVi.Properties.ReadOnly = true;
            //button xu ly su kien------------------
            btnXacNhan.Enabled = true;
        }

        //set value-------------------------------------------------------
        private void grdLyDoHoan_EditValueChanged(object sender, EventArgs e)
        {
            if (Uit.it_Parse.ToString(grdLyDoHoan.EditValue) != "-1" || Uit.it_Parse.ToString(grdLyDoHoan.EditValue) != "")
            {
                dxErrorProvider1.ClearErrors();
            }
            if (grdLyDoHoan.EditValue != null)
            {
                sIDSearch = grdLyDoHoan.EditValue.ToString();
                sTenValueSearch = grdLyDoHoan.Text;
                dxErrorProvider1.SetError(grdLyDoHoan, "");
            }
        }


        private void gvDanhSachHoanTien_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            GridView vht = gvDanhSachHoanTien;
            GridColumn colslh = vht.Columns["SoLuongHoan"];
            GridColumn colsl = vht.Columns["SoLuong"];

            int iSL = Uit.it_Parse.ToInteger(vht.GetRowCellValue(e.RowHandle, colsl).ToString());
            int iSLH = Uit.it_Parse.ToInteger(vht.GetRowCellValue(e.RowHandle, colslh).ToString());

            if (iSLH > iSL)
            {
                e.Valid = false;
                vht.SetColumnError(colslh, "Số lượng hoàn phải nhỏ hơn hoặc bằng số lượng");
                return;
            }

        }

        void m_SetNullValue()
        {
            //thong tin tim---------------------
            txtSobn.Text = "";
            txtSohs.Text = "";
            txtSTT.Text = "";
            //Thong tin chi tiet---------------
            txtSohsHT.Text = "";
            txtHoTenHT.Text = "";
            txtGioiTinhHT.Text = "";
            txtNamSinhHT.Text = "";
            txtDiaChiHT.Text = "";
            txtSobnHT.Text = "";
            txtNgay.Text = "";
            grdLyDoHoan.EditValue = -1;
            txtTongTienHoan.Text = "";
            txtTenDonVi.Text = "";
            hoanTienDto.SSobn = txtSobn.Text;
            hoanTienDto.SSohs = txtSohs.Text;
            hoanTienDto.ISTT = txtSTT.Text == "" ? 0 : Uit.it_Parse.ToInteger(txtSTT.Text);
            if (txtSobn.Text == "")
            {
                DataTable dthtct = hoanTienCtl.m_LoadHoanTienBafee(hoanTienDto).Tables[1];
                gdDanhSachHoanTien.DataSource = dthtct;
            }
            if (txtSohs.Text != "" || txtSTT.Text != "")
            {
                DataTable dtHoanTienChiTiet = hoanTienCtl.m_LoadBenhnhanHoanTien(hoanTienDto).Tables[1];
                gdDanhSachHoanTien.DataSource = dtHoanTienChiTiet;

            }
                                
            
        }
        #endregion

        private void btnThoat_CheckedChanged(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnIn_Click(object sender, EventArgs e)
        {

        }

        private void btnBoQua_Click(object sender, EventArgs e)
        {
            m_SetNullValue();
        }

        private void gdDanhSachHoanTien_KeyDown(object sender, KeyEventArgs e)
        {
            ColumnView View = (ColumnView)gdDanhSachHoanTien.FocusedView;
            GridColumn column = View.Columns["SoLuongHoan"];
            if (column != null)
            {
                View.FocusedColumn = column;
            }
        }

        private void btnTim_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                grdLyDoHoan.Focus();
            }
        }

        private void grdLyDoHoan_Enter(object sender, EventArgs e)
        {
            SendKeys.Send("{F4}");
        }

        private void gridLookUpEdit1View_CellValueChanging(object sender, CellValueChangedEventArgs e)
        {
            sTenTam = e.Value.ToString();
            sColTam = e.Column.FieldName;
        }

        private void gridLookUpEdit1View_ColumnFilterChanged(object sender, EventArgs e)
        {
            ColumnView view = grdLyDoHoan.Properties.View;
            view.ActiveFilter.Add(view.Columns[sColTam],
              new ColumnFilterInfo("[" + sColTam + "] Like '%" + sTenTam + "%'", ""));
        }

        
    }
}